<?php

/**
 * 运营平台->拍单跟踪日志拆分为单条记录
 * @author Xmh
 */
exit;
date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);
if (isset($_SERVER['REQUEST_URI'])) {
    die('error');
}

if (!defined('API_ROOT_PATH')) {
    define('API_ROOT_PATH', dirname(__FILE__));
}

require(API_ROOT_PATH . '/../inc/Config.php');
require(API_ROOT_PATH . '/../inc/MysqliDb.php');

//初始化数据库链接
function init_db() {
    $db = new MysqliDb([
        'host' => MYSQLDB,
        'username' => MYSQLDB_USER,
        'password' => MYSQLDB_PWD,
        'db' => MYSQLDB_DATABASE,
        'port' => 3306,
        'prefix' => 'au_',
        'charset' => 'utf8'
    ]);
    return $db;
}

function getNextSleepSecond() {
    $date1 = time();
    $date2 = date('Y-m-d H:i:s', strtotime('+1 hour', $date1));

    $date2 = strtotime($date2);
    $s = $date2 - $date1;

    $date1 = date('Y-m-d H:i:s', $date1);
    $date2 = date('Y-m-d H:i:s', $date2);

    logUtil("current_time:$date1  next_time:$date2  timediff:$s", 'INFO');

    return $s;
}

/**
 * 根据员工名称获取员工ID
 * @param $emp_name
 *
 * @return int
 */
function get_emp_id($emp_name){
    global $db;
    return $db->where('real_name', $emp_name)->getOne('employee', 'emp_id');
}


/**
 * 根据操作名称获取操作编号
 * @param string $action_name
 * @return int action_no
 */
function get_action_no($action_name){
    global $action;
    $action = array(
        '1001' => '开始上拍',
        '1002' => '上拍审核成功',
        '1003' => '上拍审核失败',
        '1004' => '驳回上拍成功',
        '1005' => '驳回上拍失败',
        '1006' => '开始投标',
        '1007' => '开始竞拍',
        '1008' => '竞拍结束',

        '2001' => '车主确认，成交',
        '2002' => '车主确认，磋商',
        '2003' => '车主确认，重拍',
        '2004' => '重拍',
        '2005' => '车主确认，继续跟踪',
        '2006' => '车主确认，不卖',
        '2007' => '车主确认失败，重拍',
        '2008' => '车主不卖',
        '2009' => '双方磋商，成功',
        '2010' => '双方磋商，重拍',
        '2011' => '双方磋商，继续跟踪',
        '2012' => '双方磋商，不卖',
        '2013' => '拍单失败',
        '2014' => '双方磋商，跟踪分配',
        '2015' => '车主确认，跟踪分配',

        '3001' => '违约车辆，重拍',
        '3002' => '违约车辆，退车',
        '3003' => '违约车辆，其他渠道成交',
        '3004' => '确认回车',
        '3005' => '确认到店',
        '3006' => '复检核实无误',
        '3007' => '复检继续跟踪',
        '3008' => '复检车况不符',
        '3009' => '签约分配成功',
        '3010' => '签约跟踪',
        '3011' => '签约成功',
        '3012' => '签约失败',

        '4000' => '车商验车，发送短信',
        '4001' => '车商验车，通知验车',
        '4002' => '车商验车，验车成功',
        '4003' => '车商验车，车况不符',
        '4004' => '车商验车，超时违约',
        '4005' => '车商付款跟踪',
        '4006' => '车商付款超时',
        '4007' => '车商过户争议，协商成功',
        '4008' => '车商争议，协商成功',
        '4009' => '车商争议，违约扣款',
        '4010' => '我方违约，违约补偿',
        '4011' => '车主争议，协商成功',
        '4012' => '车主争议，车主不卖',
        '4013' => '过户争议',
        '4014' => '过户跟踪',
        '4015' => '开始过户',
        '4016' => '过户完成',

        '5001' => '确认收款',
        '5002' => '核实收款',
        '5003' => '确认付首款',
        '5004' => '确认付尾款',
        '5005' => '已退车款',
        '5006' => '已收退款',
        '5007' => '车主补偿',
        '5008' => '车商补偿',

        '1101' => '第一名车商确认收车',
        '1102' => '车商违约',
        '1103' => '待签约',
        '1200' => '交易失败'
    );
    $action_diff = array(
        '车主确认成功' => '车主确认，成交',
        '车主确认,磋商' => '车主确认，磋商',
        '跟踪车主确认'  => '车主确认，继续跟踪',

        '车辆违约,重拍' => '违约车辆，重拍',
        '车辆违约,退车' => '违约车辆，退车',
        '车辆违约,其他渠道成交'=>'违约车辆，其他渠道成交',

        '磋商成功'     => '双方磋商，成功',
        '磋商继续跟踪' => '双方磋商，继续跟踪',

        '付款超时'     => '车商付款超时',
        '分配成功'     => '签约分配成功'
    );
    if(array_key_exists($action_name, $action_diff)){
        $action_name = $action_diff[$action_name];
    }
    $action_no_arr =  array_keys($action, $action_name);
    if(!empty($action_no_arr[0])){
        return $action_no_arr[0];
    }
}


//初始化redis
function init_redis()
{
    $redis = new Redis();
    $redis->connect(REDIS_HOST, REDIS_PORT);
    return $redis;
}

$db = init_db();
$redis = init_redis();

while (true) {
//判断数据库链接状态
    if (!$db->ping()) {
        $db = init_db();
    }
    $is_limit = $redis->get('update_order_trace_log_count');
    if(!$is_limit){
        $redis->set('update_order_trace_log_count', 0);
        $limit = 0;
    }else{
        $limit = $is_limit;
    }
    $size = 1;
    $order_trace_log = $db->orderBy('ot_id', 'ASC')
        ->get('order_trace_log', [$limit, $size], 'order_id,car_id,action_log');
    $order_action_log = array();
    if(!empty($order_trace_log)) {
        foreach ($order_trace_log as $oa => $ov) {
            $action_log[$oa] = array_filter(explode("/n/t", $ov['action_log']));
            foreach ($action_log[$oa] as $al => $av) {
                $action_log = explode('/t', $av);
                $action_log_arr['order_id'] = $ov['order_id'];
                $action_log_arr['car_id'] = $ov['car_id'];
                $employee = get_emp_id($action_log[2]);
                $action_log_arr['emp_id'] = $employee['emp_id'] ? $employee['emp_id'] : 0;
                $action_log_arr['emp_name'] = $action_log[2];
                $action_no = get_action_no($action_log[1]);
                $action_log_arr['action_no'] = $action_no ? $action_no : 0;
                $action_log_arr['action_name'] = $action_no ? $action[$action_no] : $action_log[1];
                $action_log_arr['createtime'] = strtotime($action_log[0])*1000;
                $order_action_log[$oa][$al] = $action_log_arr;
            }
        }
        $res = false;
        foreach ($order_action_log as $vk => $vt) {
            foreach ($vt as $kt => $tv) {
                $res = $db->insert('order_trace_log_list', $tv);
                if (!$res) {
                    logUtil("Update Order_trace_log  failed order_id:" . $tv['order_id'] . " = " . $tv['action_name'] . " = " . $tv['action_no'] . ", 'ERROR'");
                    continue;
                } else {
                    logUtil("Update Order_trace_log  success order_id:" . $tv['order_id'] . " = " . $tv['action_name'] . " = " . $tv['action_no'] . ", 'INFO'");
                }
            }
        }
        $redis->incrBy('update_order_trace_log_count', $size);
    }else{
        $sleeptimes = getNextSleepSecond();
        logUtil("Update Order_trace_log start will sleep:" . $sleeptimes . ",'INFO'");
        sleep($sleeptimes);
    }
}

/**
 * 日志记录方法
 * @param $msg
 * @param string $level DEBUG,INFO,WARN,ERR
 */
function logUtil($msg, $level = "INFO") {

    $cost_mem = memory_usage();
    $log = "[{$level}][" . date('Y-m-d H:i:s') . "][{$cost_mem}]\t{$msg}\n";
    echo $log;
    unset($log);
}

function memory_usage() {
    $memory = (!function_exists('memory_get_usage')) ? '0' : round(memory_get_usage() / 1024 / 1024, 2) . 'MB';
    return $memory;
}
